package gspushmq.v1.app.subscribeapp.utils;


import java.util.Date;
import java.util.Set;

import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.push.model.v20160801.CancelPushRequest;
import com.aliyuncs.push.model.v20160801.CancelPushResponse;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.aliyuncs.push.model.v20160801.QueryTagsRequest;
import com.aliyuncs.push.model.v20160801.QueryTagsResponse;
import com.aliyuncs.utils.ParameterHelper;
import com.google.common.collect.Sets;

import gspushmq.v1.app.subscribeapp.config.Client;
import gspushmq.v1.app.subscribeapp.models.AndroidMessge;
import gspushmq.v1.app.subscribeapp.models.IOSMessge;
import gspushmq.v1.app.subscribeapp.models.Message;


/**
 * @Description 阿里云推送工具类
 * @Author chengsj
 * @Date 2018/9/10 15:19
 * @Version 1.0
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2015 SunTime Co'Ltd Inc. All rights reserved.
 **/
public class AliPushHelper {


    /**
     * 推送高级接口
     * <p>
     * 参见文档 https://help.aliyun.com/document_detail/48089.html
     * //
     */
    public static String advancedPush(Message message) throws Exception {

        PushRequest pushRequest = new PushRequest();
        pushRequest.setProtocol(ProtocolType.HTTPS);
        pushRequest.setMethod(MethodType.POST);
        pushRequest.setAppKey(message.getAppKey());
        pushRequest.setTarget(message.getTarget());
        pushRequest.setTargetValue(message.getTargetValue());
        pushRequest.setPushType(message.getPushType());
        pushRequest.setDeviceType(message.getDeviceType());
        pushRequest.setTitle(message.getTitle());
        pushRequest.setBody(message.getBody());
        if (message instanceof IOSMessge) {
            setIOS(pushRequest, (IOSMessge) message);
        }
        if (message instanceof AndroidMessge) {
            setAndroid(pushRequest, (AndroidMessge) message);
        }
        Date pushDate = message.getPushDate();
        String pushTime = ParameterHelper.getISO8601Time(pushDate);
        pushRequest.setPushTime(pushTime);
        String expireTime = ParameterHelper.getISO8601Time(new Date(pushDate.getTime() + message.getExpireTime()));
        pushRequest.setExpireTime(expireTime);
        pushRequest.setStoreOffline(message.getStoreOffline());
        PushResponse pushResponse = Client.getInstance().getAcsResponse(pushRequest);
        return pushResponse.getMessageId();
    }

    /**
     * 取消定时推送
     * <p>
     * //
     */
    public static void cancelPush(Long id, Long appKey) throws Exception {
        CancelPushRequest request = new CancelPushRequest();
        request.setAppKey(appKey);
        request.setMessageId(id);
        CancelPushResponse response = Client.getInstance().getAcsResponse(request);
        System.out.println(response.getRequestId());
    }

    /**
     * 查询TAG(查询指定账户的tag集合)
     * https://help.aliyun.com/document_detail/48081.html?
     */

    public static Set<String> queryTag(Long appKey, String keyType, String clientKey) throws Exception {
        QueryTagsRequest request = new QueryTagsRequest();
        request.setAppKey(appKey);
        request.setKeyType(keyType);
        request.setClientKey(clientKey);

        QueryTagsResponse response = Client.getInstance().getAcsResponse(request);
        Set<String> tags = Sets.newHashSet();
        for(QueryTagsResponse.TagInfo info : response.getTagInfos()){
            tags.add(info.getTagName());
        }
        return tags;
    }


    private static void setAndroid(PushRequest pushRequest, AndroidMessge messge) {
        pushRequest.setAndroidNotifyType(messge.getAndroidNotifyType());//通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音
        pushRequest.setAndroidNotificationBarType(messge.getAndroidNotificationBarType());//通知栏自定义样式0-100
        pushRequest.setAndroidNotificationBarPriority(messge.getAndroidNotificationBarPriority());//通知栏自定义样式0-100
        pushRequest.setAndroidOpenType(messge.getAndroidOpenType()); //点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
        pushRequest.setAndroidOpenUrl(messge.getAndroidOpenUrl()); //Android收到推送后打开对应的url,仅当AndroidOpenType="URL"有效
        pushRequest.setAndroidActivity(messge.getAndroidActivity()); // 设定通知打开的activity，仅当AndroidOpenType="Activity"有效
        pushRequest.setAndroidMusic(messge.getAndroidMusic()); // Android通知音乐
        pushRequest.setAndroidExtParameters(messge.getExtParameters()); //拓展参数
        pushRequest.setAndroidNotificationChannel(messge.getAndroidNotificationChannel());//8.0特殊处理
        //小米设置
        pushRequest.setAndroidXiaoMiActivity(messge.getAndroidXiaoMiActivity());//设置该参数后启动小米托管弹窗功能, 此处指定通知点击后跳转的Activity（托管弹窗的前提条件：1. 集成小米辅助通道；2. StoreOffline参数设为true）
        String title = messge.getTitle();
        String body = messge.getBody();
        if (title != null && title.length()>16)
            title = title.substring(0,12) + "...";
        pushRequest.setAndroidXiaoMiNotifyTitle(title);//小米标题只有16个字符
        if (body != null && body.length()>128)
            body = body.substring(0,125) + "...";
        pushRequest.setAndroidXiaoMiNotifyBody(body);
        pushRequest.setAndroidXiaoMiNotifyBody(body);
        //辅助窗口
        pushRequest.setAndroidPopupTitle(title);
        pushRequest.setAndroidPopupBody(body);
        pushRequest.setAndroidPopupActivity(messge.getAndroidPopupActivity());
    }


    private static void setIOS(PushRequest pushRequest, IOSMessge messge) {
        pushRequest.setIOSBadge(messge.getiOSBadge()); // iOS应用图标右上角角标
        pushRequest.setIOSBadgeAutoIncrement(messge.getiOSBadgeAutoIncrement());
        pushRequest.setIOSSilentNotification(messge.getiOSSilentNotification());//开启静默通知
        pushRequest.setIOSMusic(messge.getiOSMusic()); // iOS通知声音
        pushRequest.setIOSSubtitle(messge.getiOSSubtitle());//iOS10通知副标题的内容
        pushRequest.setIOSNotificationCategory(messge.getiOSNotificationCategory());//指定iOS10通知Category
        pushRequest.setIOSMutableContent(messge.getiOSMutableContent());//是否允许扩展iOS通知内容
        pushRequest.setIOSApnsEnv(messge.getiOSApnsEnv());//iOS的通知是通过APNs中心来发送的，需要填写对应的环境信息。"DEV" : 表示开发环境 "PRODUCT" : 表示生产环境
        pushRequest.setIOSRemind(messge.getiOSRemind()); // 消息推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次。注意：离线消息转通知仅适用于生产环境
        pushRequest.setIOSRemindBody(messge.getiOSRemindBody());//iOS消息转通知时使用的iOS通知内容，仅当iOSApnsEnv=PRODUCT && iOSRemind为true时有效
        pushRequest.setIOSExtParameters(messge.getExtParameters()); //通知的扩展属性(注意 : 该参数要以json map的格式传入,否则会解析出错)
    }




}
